# -*- coding: utf-8 -*-
# author: sixmillions
# date: 2022/3/16

# 字典 key value类型，通过key访问value，key不重复

# 初始化
d1 = {1: "A", 2: 22}
print(type(d1))
print({"name": "sixmillions", "age": 15})
# 空字典
print(type({}))  # <class 'dict'>
print(len({}))  # 0

# 使用方式，通过key访问value
d2 = {"name": "sixmillions", "age": 15, "sex": 1}
print(d2["name"])  # sixmillions

# 不能有重复key
d3 = {"name": "sixmillions", "name": "百万", "age": 15, "sex": 1}
print(d3)  # {'name': '百万', 'age': 15, 'sex': 1}

# 赋值
d3['website'] = 'sixmillions.cn'
print(d3)  # {'name': '百万', 'age': 15, 'sex': 1, 'website': 'sixmillions.cn'}

# key必须是不可变类型：数字，str，tuple； value任意类型
d4 = {1: "A", "1": "字符1", "fun": ["BBB", "CCC"]}
print(d4[1])  # A
print(d4["1"])  # 字符1
print(d4["fun"])  # ['BBB', 'CCC']
print({(1, 3): "举例key是元组的情况"})  # {(1, 3): '举例key是元组的情况'}

# 所有key
print(d4.keys())  # dict_keys([1, '1', 'fun'])
# 所有values
print(d4.values())  # dict_values(['A', '字符1', ['BBB', 'CCC']])

# 其他方式构建字典
# 列表和元组
print(dict([('name', 'sixmillions'), ('age', 18), ('site', ['baidu.com', 'sixmillions.cn'])]))
# 结果：{'name': 'sixmillions', 'age': 18, 'site': ['baidu.com', 'sixmillions.cn']}
# 推导式
print({x: x ** 2 for x in (2, 4, 6)})  # {2: 4, 4: 16, 6: 36}
# 参数类型
print(dict(name='sixmillions', Google=2, Taobao=3))  # {'name': 'sixmillions', 'Google': 2, 'Taobao': 3}
